package com.kuang.dao.user;

import com.kuang.dao.BaseDao;
import com.kuang.pojo.Role;
import com.kuang.pojo.User;
import com.mysql.jdbc.StringUtils;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class UserDaoImpl implements UserDao{

    //得到要登录的用户
    public User getLoginUser(Connection connection, String userCode) {
        PreparedStatement pstm = null;
        ResultSet rs = null;
        User user = null;
        if(connection!=null){
            String sql = "select * from smbms_user where userCode=?";
            Object param [] = {userCode};

            try {
                rs = BaseDao.execute(connection,pstm,rs,sql,param);

                if(rs.next()){
                    user = new User();
                    user.setId(rs.getInt("id"));
                    user.setUserCode(rs.getString("userCode"));
                    user.setUserName(rs.getString("userName"));
                    user.setUserPassword(rs.getString("userPassword"));
                    user.setGender(rs.getInt("gender"));
                    user.setBirthday(rs.getDate("birthday"));
                    user.setPhone(rs.getString("phone"));
                    user.setAddress(rs.getString("address"));
                    user.setUserRole(rs.getInt("userRole"));
                    user.setCreatedBy(rs.getInt("createdBy"));
                    user.setCreationDate(rs.getTimestamp("creationDate"));
                    user.setModifyBy(rs.getInt("modifyBy"));
                    user.setModifyDate(rs.getTimestamp("modifyDate"));
                }
                BaseDao.close(null,pstm,rs);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return user;
    }

    //修改当前用户密码
    public int updatePwd(Connection connection, int id, String password) {

        PreparedStatement prsm = null;
        int execute = 0;
        if(connection!=null){
            String sql = "update smbms_user set userPassword=? where id = ?";
            Object params [] = {password,id};
            try {
                execute = BaseDao.execute(connection,prsm,sql,params);
            } catch (Exception e) {
                e.printStackTrace();
            }
            BaseDao.close(null,prsm,null);
        }
        return execute;
    }

    //根据用户名或者用户角色查询用户总数
    public int getUserCount(Connection connection, String userName, int userRole) throws Exception {
        PreparedStatement pstm = null;
        ResultSet resultSet = null;
        int count = 0;
        if (connection != null) {
            StringBuffer sql = new StringBuffer();
            sql.append("select count(*) as count from smbms_user u,smbms_role r where u.userRole=r.id ");
            //定义一个列表，用于存放我们的参数
            ArrayList<Object> list = new ArrayList<Object>();

            if (!StringUtils.isNullOrEmpty(userName)) {
                System.out.println("1");
                sql.append(" and u.userName like ?");
                list.add("%" + userName + "%");
            }
            if (userRole > 0) {
                System.out.println("2");
                sql.append(" and u.userRole = ?");
                list.add(userRole);
            }

            //把list转换成数组
            Object[] params = list.toArray();

            //System.out.println("UserDaoImpl--->getUserCount():" + sql.toString());

            resultSet = BaseDao.execute(connection, pstm, resultSet, sql.toString(), params);
            if (resultSet.next()) {
                System.out.println("进入count");
                count = resultSet.getInt(1);
                System.out.println(count);
            }
            BaseDao.close(null, pstm, resultSet);
        }
        return count;
    }

    //获取用户列表
    public List<User> getUserList(Connection connection, String userName, int userRole, int currentPageNo, int pageSize) throws Exception {
        PreparedStatement pstm = null;
        ResultSet rs = null;
        List<User> userList = new ArrayList<User>();
        if (connection != null) {
            StringBuffer sql = new StringBuffer();
            sql.append("select u.*,r.roleName as userRoleName from smbms_user u,smbms_role r where u.userRole = r.id ");
            List<Object> list = new ArrayList<Object>();
            if (!StringUtils.isNullOrEmpty(userName)) {
                sql.append(" and u.userName like ?");
                list.add("%" + userName + "%");
            }
            if (userRole > 0) {
                sql.append(" and u.userRole =?");
                list.add(userRole);
            }
            //在数据库中，分页使用 limit startIndex，pagesize；总数
            //当前页（当前页-1）*页面大小
            //0，  5      1    0       01234
            //5，  5      2    5       26789
            //10， 5      3    10
            sql.append(" order by creationDate DESC limit ?,?");
            currentPageNo = (currentPageNo - 1) * pageSize;
            list.add(currentPageNo);
            list.add(pageSize);

            Object[] params = list.toArray();
            //System.out.println("sql---->" + sql.toString());
            rs = BaseDao.execute(connection, pstm, rs, sql.toString(), params);
            while (rs.next()) {
                User _user = new User();
                _user.setId(rs.getInt("id"));
                _user.setUserCode(rs.getString("userCode"));
                _user.setUserName(rs.getString("userName"));
                _user.setGender(rs.getInt("gender"));
                _user.setBirthday(rs.getDate("birthday"));
                _user.setPhone(rs.getString("phone"));
                _user.setUserRole(rs.getInt("userRole"));
                _user.setUserRoleName(rs.getString("userRoleName"));
                userList.add(_user);
            }
            BaseDao.close(null, pstm, rs);
        }
        return userList;
    }

    //添加用户
    public int add(Connection connection, User user) throws Exception {
            PreparedStatement pstm = null;
            int addRows = 0;
            if (connection != null) {
                String sql = "insert into smbms_user (userCode,userName,userPassword," +
                        "userRole,gender,birthday,phone,address,creationDate,createdBy) " +
                        "values(?,?,?,?,?,?,?,?,?,?)";
                Object[] params = {user.getUserCode(), user.getUserName(), user.getUserPassword(),
                        user.getUserRole(), user.getGender(), user.getBirthday(),
                        user.getPhone(), user.getAddress(), user.getCreationDate(), user.getCreatedBy()};
                addRows = BaseDao.execute(connection, pstm, sql, params);
                BaseDao.close(null, pstm, null);
            }
            return addRows;
        }

    //删除用户
    public int delete(Connection connection, int id) {
        PreparedStatement pstm = null;
        int delete = 0;
        if(connection!=null){
            String sql = "delete from smbms_user where id=?";
            Object [] params = {id};
            try {
                delete = BaseDao.execute(connection,pstm,sql,params);
            } catch (Exception e) {
                e.printStackTrace();
            }finally {
                BaseDao.close(null,pstm,null);
            }
        }
        return delete;
    }

    //修改用户
    public int userModify(Connection connection, User user) throws Exception {
        PreparedStatement pstm = null;
        int updateRows = 0;
        if (connection != null) {
            String sql = "update smbms_user set userName=?," +
                    "gender=?,birthday=?,phone=?,address=?,userRole=?,modifyBy=?,modifyDate=? where id = ? ";

            Object[] params = {user.getUserName(), user.getGender(), user.getBirthday(),
                    user.getPhone(), user.getAddress(), user.getUserRole(), user.getModifyBy(),
                    user.getModifyDate(), user.getId()};
            updateRows = BaseDao.execute(connection, pstm, sql, params);
            BaseDao.close(null, pstm, null);
        }
        return updateRows;
    }

    //根据id查询用户
    public User selectById(Connection connection, int id) {
        PreparedStatement prsm = null;
        ResultSet rs = null;
        User user = null;
        if(connection != null){
            String sql = "select * from smbms_user where id = ?";
            Object [] params = {id};
            try {
                rs =  BaseDao.execute(connection,prsm,rs,sql,params);
                if(rs.next()){
                    user = new User();
                    user.setId(rs.getInt("id"));
                    user.setUserCode(rs.getString("userCode"));
                    user.setUserName(rs.getString("userName"));
                    user.setUserPassword(rs.getString("userPassword"));
                    user.setGender(rs.getInt("gender"));
                    user.setBirthday(rs.getDate("birthday"));
                    user.setPhone(rs.getString("phone"));
                    user.setAddress(rs.getString("address"));
                    user.setUserRole(rs.getInt("userRole"));
                    user.setCreatedBy(rs.getInt("createdBy"));
                    user.setCreationDate(rs.getTimestamp("creationDate"));
                    user.setModifyBy(rs.getInt("modifyBy"));
                    user.setModifyDate(rs.getTimestamp("modifyDate"));
                }
                BaseDao.close(null,prsm,rs);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return user;
    }

}
